package com.farm.view.convertor.impl;

import java.net.ConnectException;

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.farm.view.convertor.FileConvertorInter;
import com.farm.view.model.ViewFileModelInter;
import com.farm.view.model.utils.OpenOffceUtils;
import com.farm.view.task.domain.ConvertTaskFile;

public class OpenOfficeConvertor implements FileConvertorInter {

	@Override
	public String getKey() {
		return "OPENOFFICE_TO_FILE";
	}

	@Override
	public String getTitle() {
		return "Openoffice转换器";
	}

	@Override
	public String getNote() {
		return "(.doc、.docx、.xls、.ppt，txt等)转化为html或pdf格式";
	}

	@Override
	public void doConvert(ConvertTaskFile fileinfo, ViewFileModelInter omodel, ViewFileModelInter tmodel) {
		OpenOfficeConnection con = null;
		try {
			con = OpenOffceUtils.openConnection();
		} catch (ConnectException e) {
			throw new RuntimeException("openoffice无法链接:" + e.getMessage());
		}
		try {
			DocumentConverter converter = new OpenOfficeDocumentConverter(con);
			DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
			DocumentFormat oFormat = formatReg.getFormatByFileExtension(fileinfo.getExname().toLowerCase());
			DocumentFormat tFormat = formatReg
					.getFormatByFileExtension(tmodel.getExname(fileinfo.getExname()).toLowerCase());
			converter.convert(omodel.getModelFile(fileinfo.getFile(), fileinfo.getExname()), oFormat,
					tmodel.getModelFile(fileinfo.getFile(), fileinfo.getExname()), tFormat);
			//资源改写的逻辑在TaskDispatcher的run方法中，通过viewTaskServiceImpl.submitTaskSuccess(task.getTaskId());中的逻辑实现
		} catch (Exception e) {
			throw new RuntimeException("openoffice转换异常:" + e.getMessage());
		} finally {
			// 关闭openoffice连接
			con.disconnect();
		}
	}

}
